package com.didispace.web;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 处理消息组件和项目中的PropertySourcesPlaceholderConfigurer冲突
 * @author boom
 *
 */
@Component
public class PropertyProcessor implements BeanFactoryPostProcessor, EnvironmentAware {

	private ConfigurableEnvironment environment;

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = (ConfigurableEnvironment) environment;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		YamlPropertiesFactoryBean yamlspring = new YamlPropertiesFactoryBean();
		List<Resource> list = new ArrayList<Resource>();
		list.add(new ClassPathResource("test.yml"));
		yamlspring.setResources(list.toArray(new Resource[list.size()]));
		Properties prop = yamlspring.getObject();
		environment.getPropertySources().addAfter(
				StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
				new PropertiesPropertySource("config.yml", prop));
	}


}
